<template>
	
  <uni-list :border="true">
    <uni-list-chat
        v-for="(message, index) in messages"
        :key="index"
        :avatar-circle="true"
        :title="nickName"
        :avatar="transformAvatar(message.avatarUrl)"
        :note="message.messagecontent"
        :time="message.sendtime"
        badge-positon="left"
        badge-text="dot"
        clickable
        @click="goPagePrivateChat(message)"
    ></uni-list-chat>
  </uni-list>

</template>

<script>
import request from '../../../utils/request'
import {getUserId} from '../../../utils/auth.js'

export default {
  data() {
    return {
      userId: '',
      title: '',// 聊天对象
      messages: [],
      nickName:'',
      avatarUrl:''
    }
  },

  onReady() {
	  this.getMessagesList()
	  console.log(this.messages)
  },

  onLoad(optinos) {
	this.getMessagesList()
  },

  onUnload() {
  },
  destroyed() {
  },
  mounted() {
  },
  updated() {
  	
  },
  onShow() {
	this.getMessagesList()
	this.refreash()
  },

  methods: {
	  //转换图片链接
	  transformAvatar(v) {
	  	if(v == null) return '/static/images/user/ico.png'
	  	return v.replaceAll('?','%3F').replaceAll('=','%3D')
	  },
		
	refreash(){
		// uni.startPullDownRefresh({
		// 	success() {
		// 		this.getMessagesList()
		// 	}
		// })
		// setTimeout(() => {
		// //结束下拉刷新
		// uni.stopPullDownRefresh ();
		// }, 500);
		this.getMessagesList()
	},
	async getNickNameById(userId) {
	  const res = await request({
		url: `/userInfo/getNickNameById?userId=${userId}`,
	  });
	  this.nickName = res.data.nickName;
	},

	async getMessagesList() {
	  this.userId = getUserId();
	  const res = await request({
		url: `/messages/getMessagesLists?userId=${this.userId}`,
	  });
	  
	  // 先处理所有的异步操作
	  for (const message of res.data) {
		message.sendtime = message.sendtime?.replace('T', ' ');
		await this.getNickNameById(message.receiverid);
		message.nickName = this.nickName;
	  }
	  
	  // 然后进行 reduce 操作
	  const latestMessages = res.data.reduce((latest, message) => {
		const key = message.receiverid;
		if ((!latest[key] || latest[key].sendtime < message.sendtime)) {
		  latest[key] = message;
		}
		return latest;
	  }, {});
	  console.log(latestMessages)
	  this.messages = Object.values(latestMessages);
	},
    //跳转个人聊天页面
    goPagePrivateChat(message) {
		console.log(message)
      uni.navigateTo({
        url: `/pages/privateChat/index?receiverid=${message.receiverid}&chatObject=${message.nickName}`
      })
    }
  }
}
</script>

<style lang="scss">

</style>
